import { message, notification } from "antd";
import { clearAuthAndRedirect } from "./auth";
import type { ApiResponse } from "@/pages/system/user/types";
import debounce from "lodash/debounce";

// 导出请求配置
export const requestConfig = {
  baseURL: "http://localhost:3003/api",
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
  // 拦截器
  interceptors: {
    request: {
      onConfig: (config) => {
        
        // 打印完整请求地址
        const fullUrl = `${config.baseURL}${config.url}`;
        console.log('%c 🚀 Request URL 🚀 ', 'background: #222; color: #bada55; font-size: 16px;');
        console.log('%c Method 👉 ', 'color: #4CAF50; font-weight: bold;', config.method?.toUpperCase());
        console.log('%c URL 👉 ', 'color: #2196F3; font-weight: bold;', fullUrl);
        if (config.params) {
          console.log('%c Params 👉 ', 'color: #9C27B0; font-weight: bold;', config.params);
        }
        if (config.data) {
          console.log('%c Data 👉 ', 'color: #FF9800; font-weight: bold;', config.data);
        }
        console.log('-------------------');

        const token = localStorage.getItem("token");
        if (token) {
          config.headers = {
            ...config.headers,
            Authorization: `Bearer ${token}`,
          };
        }
        return config;
      },
      onError: (error) => {
        return Promise.reject(error);
      },
    },
    response: {
      onConfig: (response) => {
        const { data } = response;
        // 处理不同状态码
        switch (data.code) {
          case 200:
            return response;
          case 401:
            message.error(data?.message || "登录已过期，请重新登录");
            clearAuthAndRedirect();
            return Promise.reject(response);
          case 403:
            message.error(data?.message || "无权限访问");
            return Promise.reject(response);
          case 404:
            message.error(data?.message || "请求的资源不存在");
            return Promise.reject(response);
          case 500:
            message.error(data?.message || "服务器错误，请稍后重试");
            return Promise.reject(response);
          default:
            message.error(data?.message || "操作失败");
            return Promise.reject(response);
        }
      },
      onError: (error) => {
        if (error.response) {
          const { status, data } = error.response;
          const errorMessage = data?.message || "请求失败";
          if (status === 401) {
            clearAuthAndRedirect();
          }
          message.error(errorMessage);
        } else if (error.request) {
          message.error("网络连接失败，请检查网络");
        } else {
          message.error("请求配置错误");
        }
        return Promise.reject(error);
      },
    },
  },
};

const showErrorNotice = debounce((msg: string) => {
  notification.error({
    message: msg,
    duration: 5,
  });
}, 100);

// 更新HandleResParamsProps类型
export interface HandleResParamsProps<T = any> {
  api: (data?: any, params?: any, urlVal?: any) => Promise<ApiResponse<T>>;
  data?: any;
  urlVal?: any;
  params?: any;
  successCode?: number;
  codeKey?: string;
  returnKey?: keyof ApiResponse<T> | false;
  success?: {
    callBack?: (data: T) => void;
    msg?: string | boolean;
  };
  fail?: {
    callBack?: (data?: any) => void;
    msg?: string | boolean;
  };
  complete?: (data?: any) => void;
  deleyLoading?: React.Dispatch<React.SetStateAction<boolean>>;
}

export async function handleRes({
  api,
  data,
  params,
  urlVal,
  successCode = 200,
  codeKey = "code",
  success = { msg: false },
  fail = {},
  complete,
  deleyLoading,
  returnKey = "data",
}: HandleResParamsProps) {
  let timer: NodeJS.Timeout | null = null;

  deleyLoading &&
    (timer = setTimeout(() => {
      deleyLoading(true);
    }, 500));
  try {
    
    const res: any = await api(data, params, urlVal);
    let resData;
    const { [codeKey]: resCode, data: resMsg } = res;
    if (returnKey === false) {
      resData = res;
    } else if (returnKey) {
      resData = res[returnKey];
    }
    const successRes = {
      msg: false,
      ...success,
    };
    const failRes = {
      msg: true,
      ...fail,
    };
    if (resCode === successCode) {
      successRes.msg && message.success(successRes.msg === true ? "操作成功" : successRes.msg);
      successRes.callBack?.(resData);
      return Promise.resolve(resData);
    } else {
      const failMsgStr =
        typeof failRes.msg === "string" ? failRes.msg : resMsg || "";
      failRes.msg && showErrorNotice(failMsgStr);
      failRes.callBack?.(resMsg);
      return Promise.reject(failMsgStr);
    }
  } catch (error) {
    showErrorNotice(error.message);
  } finally {
    timer && clearTimeout(timer);
    deleyLoading && deleyLoading(false);
    complete?.();
  }
}

